package Chinese.Education.Identify.service;

import Chinese.Education.Identify.mapper.CourseMapper;
import Chinese.Education.Identify.mapper.StudentCourseMapper;
import Chinese.Education.Identify.pojo.Course;
import Chinese.Education.Identify.pojo.StudentCourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class StudentCourseService {

    @Autowired
    private StudentCourseMapper studentCourseMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Transactional
    public void selectCourses(String studentId, List<String> courseIds, String semester) {
        studentCourseMapper.deleleByStuId(studentId);
        List<StudentCourse> studentCourses = new java.util.ArrayList<>();
        for (String courseId : courseIds) {
            StudentCourse sc = new StudentCourse();
            sc.setStudentId(studentId);
            sc.setCourseId(courseId);
            sc.setSemester(semester);
            studentCourses.add(sc);
        }
        studentCourseMapper.insertBatch(studentCourses);
    }

    public List<StudentCourse> getStudentCourses(String studentId) {
        return studentCourseMapper.findByStudentId(studentId);
    }

    public List<StudentCourse> getStudentsForTeacher(String teacherId) {
        return studentCourseMapper.findByTeacherId(teacherId);
    }

    @Transactional
    public void gradeStudent(Integer studentCourseId, BigDecimal regularScore, BigDecimal labScore, BigDecimal examScore) {
        StudentCourse sc = new StudentCourse();
        sc.setId(studentCourseId);
        sc.setRegularScore(regularScore);
        sc.setLabScore(labScore);
        sc.setExamScore(examScore);

        BigDecimal finalScore = regularScore.add(labScore).add(examScore).divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP);
        sc.setFinalScore(finalScore);

        int creditsEarned = 0;
        if (finalScore.compareTo(new BigDecimal("60")) >= 0) {
            creditsEarned = 3;
        }
        sc.setCreditsEarned(creditsEarned);

        studentCourseMapper.updateScores(sc);
    }

    public List<Course> getSelectableCourses(String major, String grade) {
        return courseMapper.findByMajorAndGrade(major, grade);
    }

    public List<StudentCourse> searchStudentCourses(String studentId, String courseId, String semester) {
        return studentCourseMapper.searchStudentCourses(studentId,courseId,semester);
    }
}
